import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Image, ScrollView} from '@tarojs/components';
import {AtActionSheet} from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import {store2Props} from '../../selectors';
import {OSS_PATH_PREFIX, OSS_BASE_PATH_PREFIX, SECONDS_FORMAT, CODE_SUCCESS} from '../../constant';
import PageLoading from '../../../../common/PageLoading';
import moment from 'dayjs';
import CustomScrollView from '@/common/scrollview';
import 'taro-ui/dist/style/components/icon.scss';

type IInfoProps = T.IProps & T.IInfoProps;

import './PropModal.less';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/flex.scss';
import classNames from 'classnames';

// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 道具模态框
 */
export default class PropModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      pics: {
        emptyIcon: OSS_BASE_PATH_PREFIX + '/emptyGrey.png',
        closeIcon: OSS_BASE_PATH_PREFIX + '/propModalClose.png',
        propIcon: OSS_BASE_PATH_PREFIX + '/propIcon.png',
      },
      empty: {
        text: '玩法升级中',
      },
      ActionSheet: {
        title: '魔力进阶',
      },
      // 错误图片记录
      imageError: {},
      loading: {
        status: false,
        text: '',
        style: {
          border: '8rpx solid #ccc',
        },
        textStyle: {
          color: '#ccc',
        },
      },
      refresherTriggered: false,
      selectedProp: null,
    };
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    if (nextProps.main.status.loadingProp == false && this.props.main.status.loadingProp == true) {
      this.setState({
        refresherTriggered: false,
      });
    }

    // 使用道具
    if (nextProps.main.status.usingPropPossibility == false && this.props.main.status.usingPropPossibility == true) {
      if (nextProps.main.response.usePropPossibility == CODE_SUCCESS) {
        this.handleUse(this.state.selectedProp);
        Taro.showToast({
          title: '选择道具成功',
          icon: 'none',
        });
      }
    }
  }

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      visible,
      selectItem,
      actions: {action},
      main: {
        prop: {items},
        status: {loadingProp},
      },
      navbarSettings
    } = this.props;

    console.log('propmodal render visible', visible, 'loadingProp', loadingProp);
    console.log('propmodal items>>>>>>>selectItem', selectItem);

    return (
      <AtActionSheet isOpened={visible} className="propModal" onClose={this.handleCancel}  atActionSheetStyle={{top: navbarSettings.navBarHeight}}>
        {this.renderCloseIcon()}
        {this.renderTitle()}
        {this.renderListContent(items)}
      </AtActionSheet>
    );
  }

  /**
   * 渲染道具列表
   */
  renderListContent(items) {
    console.log('propsModal renderListContent items', items);

    const {
      main: {
        status: {loadingProp},
      },
      selectItem,
    } = this.props;

    const {pics, refresherTriggered} = this.state;

    console.log('propModal renderListContent items', items);

    return (
      <CustomScrollView
        scrollY
        scrollWithAnimation
        onRefresherRefresh={this.handleRreshList}
        onScrollToLower={this.handleScrollLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
        refresherBackground="#f7f7f7"
        className="propScrollView"
      >
        {items.length > 0 ? (
          <View className="propModalContent">
            {items.map((i: any, index: number) => (
              <View key={index} className="at-row item" onClick={() => this.handleSelectItem(i)}>
                <View className="at-col at-col-3 left">
                  <Image
                    src={i.propImg || pics.propIcon}
                    className="propIcon"
                    onError={(e) =>
                      this.handleImageError(e, index, {
                        propName: 'prop',
                        extraName: 'items',
                        imageState: 'propImg',
                      })
                    }
                  />
                </View>
                <View className="at-col at-col-7 middle">
                  <View className="propName">{i.propName}</View>
                  <View className="propExtraName">{i.propDesc}</View>
                  <View className="propTime">
                    <View>有效期:</View>
                    <View>{moment(i.propStartTime).format(SECONDS_FORMAT)}-</View>
                    <View>{moment(i.propEndTime).format(SECONDS_FORMAT)}</View>
                  </View>
                </View>
                <View className="at-col at-col-2 right">
                  {selectItem && selectItem.id && selectItem.id == i.id ? (
                    <View className={classNames('at-icon', 'at-icon-check-circle', 'activeIcon')}></View>
                  ) : (
                    <></>
                  )}
                </View>
              </View>
            ))}
          </View>
        ) : (
          this.renderEmptyContent()
        )}
      </CustomScrollView>
    );
  }

  /**
   * 点击选择内容
   */
  handleSelectItem = (i) => {
    const {selectItem} = this.props;
    // 判断是选中，还是取消选中
    if (selectItem && selectItem.id && selectItem.id == i.id) {
      this.handleCancel('selectedCancel');
    } else {
      // 编辑参数
      let params = {
        propId: i.propId,
      };
      this.setState({
        selectedProp: i,
      });
      this.props.actions.action.usePropPossibility(params);
    }
  };

  /**
   * 使用
   */
  handleUse = (i) => {
    console.log('propsModal handleUse i', i);
    this.props.onUse(i);
  };

  /**
   * 图片加载错误  通用
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState, extraName} = item;

    let {imageError, pics} = this.state;

    if (imageError[propName + '_' + extraName]) {
      imageError[propName + '_' + extraName] = imageError[propName + '_' + extraName].concat([index]);
    } else {
      imageError[propName + '_' + extraName] = [index];
    }
    console.log('imageError', imageError);

    let result = JSON.parse(JSON.stringify(main[propName][extraName]));
    let currentImage = imageError[propName + '_' + extraName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: pics.propIcon,
      };
    });

    this.props.actions.action.commonChange('main.' + propName + '.' + extraName, result);
  };

  /**
   * 下拉刷新列表
   */
  handleRreshList = () => {
    const {
      main: {
        prop: {
          page: {pageSize},
        },
      },
    } = this.props;

    const {refresherTriggered} = this.state;
    if (refresherTriggered) return;

    this.setState({
      refresherTriggered: true,
    });

    this.props.onQueryProp({
      pageSize,
      pageNum: 0,
      total: 0,
    });
  };

  /**
   * 拉倒底部
   */
  handleScrollLower = () => {
    const {
      main: {
        prop: {page, items},
      },
    } = this.props;

    let params = {
      ...page,
      pageNum: page.pageNum + 1,
    };

    if (params.pageNum > 0 && items.length == 0) {
      return;
    }
    // this.props.onQueryProp(params);
  };

  /**
   * 渲染加载动画
   * @returns
   */
  renderLoadingContent() {
    const {
      pics: {loadingIcon},
      loading: {status, text, style, textStyle},
    } = this.state;
    return (
      <View className="loagingContent">
        <PageLoading style={style} textStyle={textStyle} />
      </View>
    );
  }

  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 关闭按钮
   */
  renderCloseIcon() {
    const {pics} = this.state;

    return (
      <View className="modalClose" onClick={this.handleCancel}>
        <Image src={pics.closeIcon} className="closeIcon" />
      </View>
    );
  }

  /**
   * 渲染标题
   */
  renderTitle() {
    const {
      ActionSheet: {title},
    } = this.state;
    return <View className="propModalTitle">{title}</View>;
  }

  /**
   * 取消事件
   */
  handleCancel = (type) => {
    console.log('道具取消 handleCancel');
    this.props.onCancel(type);
  };
}
